package com.bosch.in.rtp1.ept.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

import com.bosch.in.rtp1.ept.manager.FXFactorManager;
import com.bosch.in.rtp1.ept.model.dto.FXFactor;
import com.bosch.in.rtp1.ept.model.dto.JsonFactors;
import com.bosch.in.rtp1.ept.model.technical.Condition4FxFactor;
import com.bosch.in.rtp1.ept.util.ConverterUtility;
import com.bosch.in.rtp1.ept.util.ManagerFactory;
import com.bosch.in.rtp1.ept.util.SQLConditionBuilder;

public class FXFactorAction extends MappingDispatchAction{
    
	private static final Logger LOGGER = Logger.getLogger(FXFactorAction.class);
	
	/**
	 * Response to ajax call from Jquery grid, it will delegate to Manager class
	 * to query FXFactor according to search criteria in request parameter.
	 * The returned list then will be transformed to JSON format in order to 
	 * display on client side.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws IOException 
	 */
	
	@SuppressWarnings("unchecked")
	public ActionForward loadFxFactors(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException 
			 {

		LOGGER.debug("Begin FXFactorAction.loadFxFactors");
		
		// build conditions from parameters in request
		Condition4FxFactor condition4FxFactor = SQLConditionBuilder.extractCondition4FXFactor(request);

		// get FXFactorManager instance
		FXFactorManager factorManager = ManagerFactory.getInstance().getFXFactorManager();
		
		// retrieve FXFactor list according to the conditions
		List<FXFactor> fxFactors = factorManager.getFXFactors(condition4FxFactor);
		ConverterUtility.fillMonth(fxFactors,condition4FxFactor);
		
    	// convert returned data in kind of JSON format which Jqgrid supports
    	JSONArray cellarray = ConverterUtility.convertToRows(fxFactors);
    	JsonFactors jsonFXFactors = new JsonFactors();
    	jsonFXFactors.setRows(cellarray);
    	
    	// write data to output stream with MIME type is text
    	String jsonResponse = JSONSerializer.toJSON(jsonFXFactors).toString();
    	response.setContentType("text/text;charset=utf-8");
    	response.setHeader("cache-control", "no-cache");
    	PrintWriter out = response.getWriter();
    	out.println(jsonResponse);
    	out.flush();
    	
    	LOGGER.debug("End FXFactorAction.loadFxFactors");
    	
    	return null;
	}
	
	/**
    * Update/Insert FXFactor object into database based on status of that object.
    * @param mapping The ActionMapping used to select this instance
    * @param form The optional ActionForm bean for this request (if any)
    * @param request The HTTP request we are processing
    * @param response The HTTP response we are creating
    * @exception Exception if an exception occurs
    * @return the ActionForward to forward control to
	 * @throws SQLException 
    */
   public ActionForward manipulateFxFactor(
       ActionMapping mapping,
       ActionForm form,
       HttpServletRequest request,
       HttpServletResponse response) throws SQLException
       {

		   LOGGER.debug("Begin FXFactorAction.manipulateFxFactor");
		   
			// get FXFactorManager instance
		   FXFactorManager fxFactorManager = ManagerFactory.getInstance().getFXFactorManager();
		   
		   // get fx factor list from request
		   List<FXFactor> fxList = ConverterUtility.convertToFXFactors(request);
	
		   fxFactorManager.updateFXFactors(fxList);
		   
	       LOGGER.debug("End FXFactorAction.manipulateFxFactor");
	       
	       return null;
   }
   
//   /**
//    * Update fx factor based on the retrieving conditions from request
//    * @param fxFactorManager
//    * @param request
//    * @param response
//    * @throws Exception
//    */
//   private void updateFXFactor(FXFactorManager fxFactorManager, HttpServletRequest request,
//		   HttpServletResponse response) throws Exception {
//	   
//	    LOGGER.debug("Begin FXFactorAction.updateFXFactor");
//	   
//	    // extract parameter from request and convert to FXFactor object
////	    FXFactor fxFactor = ConverterUtility.convertToFXFactor(request);
////	    
////	    // update FXFactor 
////		boolean success = fxFactorManager.updateFXFactors(fxFactor);
////		
////		// response to client
////		response.setContentType("text/html;charset=utf-8");
////		
////		PrintWriter out = response.getWriter();
////		if (success) 
////			{
////				out.println("Update successfully!");
////			}
////		else 
////			{
////				out.println("<font color='red'>Update fail!</font>");
////			}
////			
//		LOGGER.debug("End FXFactorAction.updateFXFactor");
//		
////		out.flush();
//   }
//   
//   /**
//    * Insert fx factor based on the retrieving conditions from request
//    * @param fxFactorManager
//    * @param request
//    * @param response
//    * @throws Exception
//    */
//   private void insertFXFactor(FXFactorManager fxFactorManager, HttpServletRequest request,
//		   HttpServletResponse response) throws Exception {
//	   
//	    LOGGER.debug("Begin FXFactorAction.insertFXFactor");
//	   
////	    // extract parameter from request and build FXFactor object
////	    FXFactor fxFactor = ConverterUtility.convertToFXFactor(request);
////	    
////	    // insert new FXFactor
////		boolean success = fxFactorManager.insertFXFactors(fxFactor);
////		
////		// response to client
////		response.setContentType("text/html;charset=utf-8");
////		PrintWriter out = response.getWriter();
////		
////		if (success) {
////			out.println("Update successfully!");
////		} else {
////			out.println("<font color='red'>Update fail!</font>");
////		}
////			
//		LOGGER.debug("End FXFactorAction.insertFXFactor");
//		
////		out.flush();
//   }

}
